package com.ykzhujiang.lovespirit.util;

import java.io.PrintWriter;
import java.util.Vector;
import java.util.logging.Logger;

import org.dom4j.Element;

import com.ykzhujiang.lovespirit.analyzer.Analyzer;
import com.ykzhujiang.lovespirit.entity.LThread;
import com.ykzhujiang.lovespirit.entity.Notice;
import com.ykzhujiang.lovespirit.parser.Parser;

public class ParserProcessor implements Runnable {
	public ParserProcessor(Parser p, Element root, String url_text) {
		this.parser = p;
		this.root = root;
		this.url_text = url_text;
	}

	public void run() {
		// logger.info("run");
		lt = (parser.Parse(url_text, Utility
				.GetURLText(url_text, connect_times)));
		if (lt == null)
			return;
		boolean flag = true;
		for (int i = 0; i < analyzers.size(); i++) {
			Analyzer a = (Analyzer) analyzers.get(i);
			if (a.Analyze(lt) == false) {
				flag = false;
				break;
			}
		}
		if (flag == true) {
			if (pw != null)
				Utility.PrintThread(pw, lt);
			Notice notice = (Notice) DataManager.getData(Notice.class,
					lt.notices.get(0).getSourceUrl(), false, null);
			if (notice != null) {
				logger.info("try to update notice");
				notice.setTitle(lt.notices.get(0).getTitle());
				notice.setContent(lt.notices.get(0).getContent());
				notice.setHot(lt.notices.get(0).getHot());
				notice.setType(lt.notices.get(0).getType());
				notice.setDate(lt.notices.get(0).getDate());
				notice.setResourceUrl(lt.notices.get(0).getResourceUrl());
				DataManager.addData(notice);
			} else {
				logger.info("try to add notice");
				DataManager.addData(lt.notices.get(0));
			}
			result_threads.add(lt);
		}
	}

	public void AddAnalyzer(Analyzer a) {
		this.analyzers.add(a);
	}

	public void SetWriter(PrintWriter writer) {
		this.pw = writer;
	}

	public Parser parser = null;

	public Vector analyzers = new Vector();

	public Element root = null;

	public String url_text = null;

	public LThread lt = null;

	public static int connect_times = 3;

	public static Vector result_threads = new Vector();

	public PrintWriter pw = null;

	private static final Logger logger = Logger.getLogger(ParserProcessor.class
			.getName());

}
